﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameRobot
{
    public class RobotBridge
    {
        public VirtualRobot _sender = null;
        List<GameMessage> _messageA = new List<GameMessage>();
        List<GameMessage> _messageB = new List<GameMessage>();
        List<GameMessage> _messageEvent = new List<GameMessage>();

        public void PushMessageA(GameMessage message)
        {
            _messageB.Add(message);
            UnLock();
        }

        public GameMessage PopMessageA()
        {
            if (_messageA.Count > 0)
            {
                GameMessage message = _messageA[0];
                _messageA.RemoveAt(0);
                return message;
            }

            return null;
        }

        public void PushMessageB(GameMessage message)
        {
            _messageA.Add(message);
        }

        public GameMessage PopMessageB()
        {
            if (_messageB.Count > 0)
            {
                GameMessage message = _messageB[0];
                _messageB.RemoveAt(0);
                return message;
            }

            return null;
        }

        public void PushMessageEvent(GameMessage message)
        {
            bool ok = false;
            for (int i = 0; i < _messageEvent.Count; i++)
            {
                if (message._priority > _messageEvent[i]._priority)
                {
                    _messageEvent.Insert(i, message);
                    ok = true;
                    break;
                }
            }
            if (!ok)
                _messageEvent.Add(message);

            UnLock();
        }

        public GameMessage PopMessageEvent()
        {
            if (_messageEvent.Count > 0)
            {
                GameMessage message = _messageEvent[0];
                _messageEvent.RemoveAt(0);
                return message;
            }

            return null;
        }

        public void Lock()
        {
            if (_sender != null)
                _sender.Pause();
        }

        public void UnLock()
        {
            if (_sender != null)
                _sender.Resume();
        }

        public void Reset()
        {
            _messageA.Clear();
            _messageB.Clear();
            _messageEvent.Clear();
            if (_sender != null)
                _sender.Stop();
            _sender = null;
        }
    }
}
